using System;
using System.Collections.Generic;
using System.Text;
using LibrErian.Common;
using System.Collections;
using LibrErian.Model;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.EventBroker;
using LibrErian.Interfaces.Data;
using LibrErian.Interfaces.Services;

namespace LibrErian.Modules.BasicBook
{
    public class ManageGenreViewPresenter : Presenter<IManageGenreView>
    {
        private IList genres;
        private IGenreService genreService;

        [ServiceDependency]
        public IGenreService GenreService
        {
            set
            {
                genreService = value;
            }
        }

        [EventPublication("event://GenresUpdated", PublicationScope.Global)]
        public event EventHandler GenresUpdated;

        private void OnGenresUpdated()
        {
            if (GenresUpdated != null)
            {
                GenresUpdated(this, EventArgs.Empty);
            }
        }
        
        private IList GetGenres()
        {
            return genreService.GetGenres();
        }

        public override void OnViewReady()
        {
            base.OnViewReady();

            genreService.StartDisconnectedSession();

            genres = GetGenres();

            View.SetGenres(genres);
        }

        public void AddItem(string name)
        {
            Genre newGenre = new Genre();
            newGenre.Name = name;
            genreService.Save(newGenre);
            genres.Add(newGenre);
            View.SetGenres(genres);
        }

        public void DeleteItem(Genre genreToRemove)
        {
            genreService.Delete(genreToRemove);
            genres.Remove(genreToRemove);
            View.SetGenres(genres);
        }
                
        public void OnOk()
        {
            genreService.EndDisconnectedSessionWithFlush();
            OnGenresUpdated();
            CloseView();
        }

        public void OnCancel()
        {
            genreService.EndDisconnectedSessionWithFlush();
            CloseView();
        }
    }

    public interface IManageGenreView
    {
        void SetGenres(IList items);
    }
}
